//
//  ELNetWorkTool.swift
//  SinaWeiBo
//
//  Created by jiwang on 15/12/17.
//  Copyright © 2015年 jiwang. All rights reserved.
//

import UIKit
import AFNetworking

enum ELNetWorkError : Int {
    case emptyAccessToken = -1
    case emptyUid = -2
    
    var emptyDescription : String {
        
        switch self {
        
        case .emptyAccessToken:
            return "accessToken没有值"
        case .emptyUid:
            return "uid没有值"
        }
    }
    
    func errorType () -> NSError {
        
        return NSError(domain: "www.badu.com.cn/error", code: self.rawValue, userInfo: ["emptyDescription" : self.emptyDescription])
    }
}

class ELNetWorkTool: AFHTTPSessionManager {

    //创建单例对象
    static let shareNetWork : ELNetWorkTool = ELNetWorkTool()
    
    private init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///appKey
    private let client_id : String = "1092506646"
    ///授权回调地址
    let redirect_uri : String = "http://www.baidu.com"
    ///apple密匙
    private let Secret : String = "95f613e4cdefdd8b8ea523ebf043435c"
    
    //示例
    //https://api.weibo.com/oauth2/authorize?client_id=1092506646&redirect_uri=http://www.baidu.com
    
    //返回请求授权url
    func oauthURL() -> NSURL {
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlStr)!
        
    }
    
    func loadAccessTocken (code : String , finished : (result : [String : AnyObject]?,error : NSError?) -> ()) {
        //请求地址
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let parameters = [
            "client_id" : client_id,
            "client_secret" : Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        //发送post请求
        POST(urlStr, parameters: parameters, success: { (_,result) -> Void in

            //返回的是一个字典
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            print(dict)
            }) { (_,error) -> Void in

                finished(result: nil, error: error)
        }
        
    }
    
    //MARK: 加载用户信息
    //请求的url ：https://api.weibo.com/2/users/show.json
    //参数1 :access_token	 string	 采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
    //参数2 :uid	false  int64  需要查询的用户ID。
    func loadUserInfo (finished : (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        //获取access_toke
        guard let access_token = ELUserAccount.loadUserAccount()?.access_token else {
            
            //进来表示没有access_token
            finished(result: nil, error: ELNetWorkError.emptyAccessToken.errorType())
            return
        }
        
        guard let uid = ELUserAccount.loadUserAccount()?.uid else {
            
            //没有uid
            finished(result: nil, error: ELNetWorkError.emptyUid.errorType())
            return
        }
        
        let url = "2/users/show.json"
        let paramerters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        
        GET(url, parameters: paramerters, success: { (_, result) -> Void in
            
            let dict = result as! [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                
                finished(result: nil, error: error)
        }
    }
    
    //MARK: 加载微博数据
    //url:https://api.weibo.com/2/statuses/home_timeline.json
    //请求参数 access_token
    func loadStatuses (finished : (result : [String : AnyObject]?,error : NSError?) -> ()) {
        
        guard let access_token = ELUserAccount.loadUserAccount()?.access_token else {
            
            //进来表示没有access_token
            finished(result: nil, error: ELNetWorkError.emptyAccessToken.errorType())
            return
        }
        
        let url = "2/statuses/home_timeline.json"
        let paramerters = ["access_token" : access_token]
        
        GET(url, parameters: paramerters, success: { (_, result) -> Void in
            
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
}
